<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    v-drag
  >
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('关闭') }}</a-button>
    </template>
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('会员信息')">
                <a-input :placeholder="$t('请输入手机号/卡号/姓名')" v-model="queryParam.memberInfo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('状态')">
                <j-dict-select-tag
                  :placeholder="$t('请选择状态')"
                  v-model="queryParam.state"
                  dictCode="bis_activity_presale_record.state"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('业务渠道')">
                <a-select v-model="queryParam.deviceType">
                  <a-select-option :value="item.value" :key="index" v-for="(item, index) in deviceinfoList">{{
                    item.title
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('设备')">
                <a-select show-search :filter-option="false" @search="handleSearch" v-model="queryParam.deviceId">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in deviceList">
                    <span>{{ item.name }}</span>
                    <span v-if="item.name != $t('全部')">({{ item.id }})</span>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('定金单号')">
                <a-input :placeholder="$t('请输入')" v-model="queryParam.id"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('定金时间')">
                <j-date
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="queryParam.depositTime_begin"
                ></j-date>
                <span>~</span>
                <j-date
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="queryParam.depositTime_end"
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('尾款时间')">
                <j-date
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="queryParam.finalTime_begin"
                ></j-date>
                <span>~</span>
                <j-date
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="queryParam.finalTime_end"
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="5" :md="6" :sm="24">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                  $t('重置')
                }}</a-button>
                <!-- <a-button type="primary" @click="handleExportXls($t('活动记录'))" style="margin-left: 8px">{{
                  $t('导出')
                }}</a-button> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- table区域-begin -->
      <div>
        <a-table
          ref="table"
          size="middle"
          :scroll="{ x: true }"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          class="j-table-force-nowrap"
          @change="handleTableChange"
        >
          <template slot="footer">
            <div>
              <span>{{ $t('定金笔数') }}：{{ total.depositNum }}</span
              ><span style="margin-left: 10px">{{ $t('定金金额') }}：{{ total.depositSum.toFixed(2) }}</span>
              <span style="margin-left: 10px">{{ $t('尾款笔数') }}：{{ total.finalPayNum }}</span
              ><span style="margin-left: 10px">{{ $t('尾款金额') }}：{{ total.finalPaySum.toFixed(2) }}</span>
            </div>
          </template>
        </a-table>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, downFile } from '@/api/manage'

export default {
  name: 'PresaleRecordsModal',
  mixins: [mixinDevice],
  components: {},
  data() {
    return {
      title: this.$t('活动记录'),
      width: 1500,
      visible: false,
      confirmLoading: false,
      activityId: '',
      deviceList: [],
      deviceinfoList: [],
      dictOptions: {},
      queryParam: {
        column: 'createTime',
        order: 'desc',
        deviceType: '',
        memberInfo: '',
        deviceId: ''
      },
      // 表头
      columns: [
        {
          title: this.$t('手机号'),
          align: 'center',
          dataIndex: 'phone',
        },
        {
          title: this.$t('卡号'),
          align: 'center',
          dataIndex: 'chipNo',
        },
        {
          title: this.$t('姓名'),
          align: 'center',
          dataIndex: 'memberName',
        },
        {
          title: this.$t('状态'),
          align: 'center',
          dataIndex: 'state_dictText',
        },
        {
          title: this.$t('定金单号'),
          align: 'center',
          dataIndex: 'id',
        },
        {
          title: this.$t('定金时间'),
          align: 'center',
          dataIndex: 'depositTime',
        },
        {
          title: this.$t('定金金额'),
          align: 'center',
          dataIndex: 'deposit',
          customRender: (text, record) => {
            return text.toFixed(2)
          },
          customCell: (text, record) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('尾款时间'),
          align: 'center',
          dataIndex: 'finalTime',
        },
        {
          title: this.$t('尾款金额'),
          align: 'center',
          dataIndex: 'finalPay',
          customRender: (text, record) => {
            if(record.state == 0){
              return ''
            }
            return text.toFixed(2)
          },
          customCell: (text, record) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务渠道'),
          align: 'center',
          dataIndex: 'deviceType_dictText',
        },
        {
          title: this.$t('设备名称'),
          align: 'center',
          dataIndex: 'deviceName',
        },
        {
          title: this.$t('设备编码'),
          align: 'center',
          dataIndex: 'deviceId',
        },
      ],
      dataSource: [],
      loading: false,
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total', { total: total })
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      url: {
        list: '/activity/bisPresaleRecord/list',
        exportXlsUrl: '/activity/bisPresaleRecord/exportXls',
      },
      total: {
        depositNum: 0,
        depositSum: 0,
        finalPayNum: 0,
        finalPaySum: 0,
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    handleSearch(value) {
      let query = {}
      if (value) {
        query.deviceInfo = value
      }
      getAction('/device/bisDeviceInfo/list', query).then((res) => {
        if (res.success) {
          this.deviceList = res.result.records
          this.deviceList.unshift({ id: '', name: this.$t('全部') })
        }
      })
    },
    initDictConfig() {
      this.handleSearch('')
      initDictOptions('bis_device_info.type').then((res) => {
        if (res.success) {
          this.deviceinfoList = res.result
          this.deviceinfoList.unshift({ value: '', title: this.$t('全部') })
        }
      })
    },
    show(record) {
      this.visible = true
      this.activityId = record.id
      this.queryParam.activityId = record.id
      this.loadData(1)
      this.initDictConfig()
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error(this.$t('请设置url.list属性'))
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.queryParam
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.getTotal()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    getTotal() {
      getAction('/activity/bisPresaleRecord/total', this.queryParam).then((res) => {
        if (res.success) {
          this.total = res.result
        } else {
          this.total.depositNum = 0
          this.total.depositSum = 0
          this.total.finalPayNum = 0
          this.total.finalPaySum = 0
        }
      })
    },
    searchQuery() {
      this.loadData(1)
    },
    handleCancel() {
      this.visible = false
    },
    searchReset() {
      this.queryParam = {
        column: 'createTime',
        order: 'desc',
        deviceType: '',
        memberInfo: '',
        deviceId: '',
        activityId: this.activityId,
      }
      this.loadData(1)
    },
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let param = this.queryParam
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      if (this.isNoPageTotal) {
        param.pageSize = 99999999
      }
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>